package com.example.musicaiap.ui.community

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.musicaiap.data.repository.MusicRepository
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.data.repository.FavoriteStateRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CommunityViewModel @Inject constructor(
    private val musicRepository: MusicRepository,
    private val favoriteStateRepository: FavoriteStateRepository
) : ViewModel() {

    private val TAG = "CommunityViewModel"

    private val _favoriteSongs = MutableStateFlow<List<Song>>(emptyList())
    val favoriteSongs: StateFlow<List<Song>> = _favoriteSongs.asStateFlow()

    private val _isLoading = MutableStateFlow(true)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    init {
        loadFavoriteSongs()

        // 订阅收藏状态变化事件
        observeFavoriteChanges()
    }

    /**
     * 订阅收藏状态变化事件
     * 优化版本：直接监听FavoriteStateRepository的状态变化
     */
    private fun observeFavoriteChanges() {
        viewModelScope.launch {
            favoriteStateRepository.favoriteChanges.collect { event ->
                // 当收到收藏状态变化事件时，刷新收藏列表
                Log.d(TAG, "收到收藏状态变化事件：songId=${event.songId}, isFavorite=${event.isFavorite}，刷新收藏列表")
                refreshFavoriteSongs()
            }
        }
    }

    private fun loadFavoriteSongs() {
        Log.d(TAG, "开始加载收藏歌曲列表")
        viewModelScope.launch {
            try {
                _isLoading.value = true
                Log.d(TAG, "获取收藏歌曲Flow")
                val favoriteSongsFlow = musicRepository.getFavoriteSongs()
                Log.d(TAG, "成功获取收藏歌曲Flow，开始收集数据")

                favoriteSongsFlow.collectLatest { songs ->
                    Log.d(TAG, "收到收藏歌曲数据: ${songs.size}首")
                    songs.forEachIndexed { index, song ->
                        Log.d(TAG, "收藏歌曲[$index]: ID=${song.id}, 标题=${song.title}")
                    }
                    _favoriteSongs.value = songs
                    _isLoading.value = false
                    Log.d(TAG, "更新收藏歌曲状态完成，是否为空：${songs.isEmpty()}")
                }
            } catch (e: Exception) {
                Log.e(TAG, "加载收藏歌曲列表失败", e)
                _isLoading.value = false
            }
        }
    }

    /**
     * 刷新收藏歌曲列表
     * 当在其他页面（如PlayerScreen）添加或移除收藏时调用此方法刷新数据
     */
    fun refreshFavoriteSongs() {
        Log.d(TAG, "手动刷新收藏歌曲列表")
        loadFavoriteSongs()
    }

    fun toggleFavorite(songId: String) {
        viewModelScope.launch {
            try {
                // 获取当前状态
                val currentState = favoriteStateRepository.getSongFavoriteState(songId)

                // 立即更新UI状态，提供即时反馈
                val newState = !currentState

                // 先更新Repository状态，这会触发UI更新
                favoriteStateRepository.setSongFavoriteState(songId, newState)

                Log.d(TAG, "切换歌曲收藏状态: $songId")
                // 在后台执行实际的数据库操作
                val actualState = musicRepository.toggleFavorite(songId)
                Log.d(TAG, "歌曲 $songId 收藏状态切换为: $actualState")

                // 确保最终状态与数据库一致
                if (actualState != newState) {
                    favoriteStateRepository.setSongFavoriteState(songId, actualState)
                }

                // 不需要手动刷新列表，因为我们已经在监听favoriteChanges事件
            } catch (e: Exception) {
                Log.e(TAG, "切换收藏状态失败", e)
                // 如果操作失败，恢复到原始状态
                val actualState = musicRepository.isSongFavorite(songId)
                favoriteStateRepository.setSongFavoriteState(songId, actualState)
            }
        }
    }
}